import { defineStore } from "pinia";
import { computed, ComputedRef, Ref, ref } from "vue";
import { pageParams, skuInfo, skuItem } from "@/api/product/skuApi/interface.ts";
import { fetchSkuListAPI, deleteSkuAPI, saleSkuAPI, cancelSkuAPI, findSkuDetailAPI } from "@/api/product/skuApi/sku.ts";

const useSkuStore = defineStore("skuStore", () => {
  const pageParams = ref<pageParams>({ page: 1, limit: 10 });

  const skuListInfo: Ref<skuInfo | undefined> = ref<skuInfo | undefined>();

  const skuList: ComputedRef<skuItem[] | undefined> = computed<skuItem[] | undefined>(() => skuListInfo?.value?.records);

  const total: ComputedRef<number | undefined> = computed<number | undefined>(() => skuListInfo.value?.total);

  const drawer = ref<boolean>(false);
  const skuDetail = ref<any>({});
  const fetchSkuListInfo = async (): Promise<void> => {
    const { data }: { data: skuInfo } = await fetchSkuListAPI(pageParams.value);
    skuListInfo.value = data;
  };

  const deleteSku = async (skuId: number): Promise<string> => {
    await deleteSkuAPI(skuId);
    return "删除成功";
  };

  const saleSkuOrCancelSku = async (sku: skuItem): Promise<string> => {
    if (sku.isSale === 0) {
      await saleSkuAPI(sku.id);
      return "上架成功";
    } else {
      await cancelSkuAPI(sku.id);
      return "下架成功";
    }
  };

  const findSkuDetail = async (skuId: number) => {
    const { data } = await findSkuDetailAPI(skuId);
    skuDetail.value = data;
  };
  return {
    pageParams,
    skuListInfo,
    skuList,
    total,
    drawer,
    skuDetail,
    fetchSkuListInfo,
    deleteSku,
    saleSkuOrCancelSku,
    findSkuDetail,
  };
});

export default useSkuStore;
